# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.shortcuts import redirect
from basic import models
from django.db.models import Q,QuerySet
from django.core.paginator import Paginator
from basic.models import instance_info
import ast
from django.http import JsonResponse, HttpResponse
# Create your views here.
from django.forms.models import model_to_dict
import json
import cx_Oracle
import time
import logging
from cron import models as cron_models
from basic import models as basic_models
from oratk import models as oratk_models

#选择实例下拉框，装饰器
from basic.utils import with_instanceinfo

logger = logging.getLogger(__name__)


def v_paginator(data, current_page_num, line_count_set):
    # 以下是分页
    # 5条一页
    # 总页数：paginator.num_pages
    # 当前页：current_page_num
    # 当前页数据：current_page
    # 总行数：paginator.count
    global paginator
    global current_page
    global page_range
    global paginator_num_pages_list
    # paginator = Paginator(data, 5)  # 对所有数据进行分页
    paginator = Paginator(data, line_count_set)
    global last_page
    last_page = paginator.num_pages

    paginator_num_pages_list = [x for x in range(1, paginator.num_pages + 1)]
    # if paginator_num_pages_list==[]:
    #     paginator_num_pages_list = [1]
    try:  # 捕捉前台传过来的数据，传过来不正常的数据都跳到第一页
        global current_page
        current_page = paginator.page(current_page_num)  # 拿哪一页
        if paginator.num_pages > 11:  # 判断总页数是否大于 10 页
            if current_page_num - 5 < 1:  # 页数小于前5页就显示前10页
                current_range = range(1, 11)
                page_range = current_range
                return current_range, current_page, paginator, page_range, last_page, paginator_num_pages_list
            elif current_page_num + 5 > paginator.num_pages:  # 页数大于最后5页就显示最后10页
                current_range = range(paginator.num_pages - 10, paginator.num_pages + 1)
                page_range = current_range
                return current_range, current_page, paginator, page_range, last_page, paginator_num_pages_list
            else:
                current_range = range(current_page_num - 4, current_page_num + 4)  # 其他范围为-5页到+5页
                page_range = current_range
                return current_range, current_page, paginator, page_range, last_page, paginator_num_pages_list
        else:
            page_range = paginator.page_range  # 小于10页就显示所有页数
            return page_range, current_page, paginator, page_range, last_page, paginator_num_pages_list

    except Exception as e:
        current_page_num = 1  # 随便乱传取第一页
        current_page = paginator.page(current_page_num)  # 随便乱传则取第一页
        current_range = range(1, 12)
        return paginator, current_page, current_range, page_range, last_page, paginator_num_pages_list


###用户登入
def mytk(request):
    error_msg = ""
    if request.method == 'POST':
        user = request.POST.get('user',None)
        pwd = request.POST.get('pwd',None)
        #request.session['username'] = user
        login_obj = models.user_info.objects.filter(username=user,password=pwd).first()
        if login_obj:
            request.session['username'] = user
            request.session['is_login'] = True
            if login_obj.status == 'LOCKED':
                error_msg = "该用户状态为'LOCKED'"
                return render(request, 'basic_app/login.html', {'error_msg': error_msg})
            # return redirect('/basic_app/user')
            return redirect('/oratk_app/oratk_query')
            # return render(request,'/basic_app/user.html',{'userinfo':user})
            #return HttpResponse("登入成功")
        else:
            error_msg = "用户名或密码错误"
            #print request.path
            return render(request, 'basic_app/login.html', {'error_msg': error_msg})
    if request.method == 'GET':
        return render(request, 'basic_app/login.html', {'error_msg':error_msg})

##ora工具功能项管理
def oratk_tool_info_ora(request):
    logger.info("Entry......")
    if request.method == 'POST':
        pass
    if request.method == 'GET':

        currentpage_num = int(request.GET.get('page', '1'))
        line_count_set = int(request.GET.get('line_count', 5))
        user_search = request.GET.get('user_search', '')
        ##返回数据
        oratk_tool_info_result = cron_models.ora_point_info.objects.filter(Q(name__contains=user_search)
                                                                           | Q(sqltext__contains=user_search)
                                                                           | Q(status__contains=user_search)
                                                                           | Q(remark__contains=user_search)
                                                                           | Q(desc__contains=user_search))

        oratk_tool_info_result = list(oratk_tool_info_result)
        v_paginator(oratk_tool_info_result, currentpage_num, line_count_set)
        # print(type(oratk_tool_info_result),oratk_tool_info_result)
        # for i in oratk_tool_info_result:
        #     print(i.sqltext)
        return render(request, 'oratk_app/my_tool_info.html',
                      {'current_page': current_page, 'paginator': paginator, 'line_count': line_count_set,
                       'page_range': page_range, 'last_page': last_page, 'current_page_num': currentpage_num,
                       'paginator_num_pages_list': paginator_num_pages_list
                          , 'search': user_search})



# mysql sql类工具 point
def my_tool_info(request):
    logger.info("Entry......")
    if request.method == 'POST':
        pass
    if request.method == 'GET':
        currentpage_num = int(request.GET.get('page', '1'))
        line_count_set = int(request.GET.get('line_count', 5))
        user_search = request.GET.get('user_search', '')
        ##返回数据
        oratk_tool_info_result = cron_models.ora_point_info.objects.filter(Q(name__contains=user_search)
                                                                           | Q(sqltext__contains=user_search)
                                                                           | Q(status__contains=user_search)
                                                                           | Q(remark__contains=user_search)
                                                                           | Q(desc__contains=user_search),db_type='MYSQL')

        oratk_tool_info_result = list(oratk_tool_info_result)
        v_paginator(oratk_tool_info_result, currentpage_num, line_count_set)
        # print(type(oratk_tool_info_result),oratk_tool_info_result)
        # for i in oratk_tool_info_result:
        #     print(i.sqltext)
        return render(request, 'mytk_app/my_tool_info.html',
                      {'current_page': current_page, 'paginator': paginator, 'line_count': line_count_set,
                       'page_range': page_range, 'last_page': last_page, 'current_page_num': currentpage_num,
                       'paginator_num_pages_list': paginator_num_pages_list
                          , 'search': user_search})




# 等待事件与锁
@with_instanceinfo(db_type='MYSQL')
def my_most_sessionevent(request,instanceinfo_result, instanceinfo_result_total):
    if request.method == 'GET':
        logger.info("Entry......")
        return render(request, 'mytk_app/my_most_sessionevent.html',
                      {'instanceinfo_result': instanceinfo_result,'instanceinfo_result_total':instanceinfo_result_total})
